package samples
{
	import by.blooddy.crypto.image.JPEGEncoder;
	import flash.events.MouseEvent;
	import flash.utils.ByteArray;
	
	import marcel.core.Plugin;
	import marcel.debug.*;
	import marcel.display.View;
	import marcel.display.gui.buttons.SimpleTextButton;
	import marcel.display.gui.components.List;
	import marcel.external.facebook.Facebook;
	import marcel.external.facebook.FacebookEvent;
	import marcel.external.facebook.data.*;
	
	public class FacebookSample extends View
	{
		private var fb:Facebook;
		
		
		public function FacebookSample()
		{
			super(50, 50, ORIENTATION_VERTICAL);
			
			// Facebook API doc :
			// http://developers.facebook.com/docs/reference/api/
			
			// in facebook app settings:
			// Web Site > Site URL = http://localhost/www/marcel-as3-framework/apps/site/
			var redirectURI:String =  "http://localhost/www/marcel-as3-framework/apps/site/callback_facebook.html"; // callback url
			var clientId:String = "146168738734269"; // facebook app id
			var permissions:String = "publish_stream,read_stream,user_likes,user_status,user_photos,user_videos,user_photo_video_tags,offline_access,user_checkins,friends_checkins";
			//http://developers.facebook.com/docs/authentication/permissions
			//publish_stream,create_event,rsvp_event,sms,offline_access,manage_pages
			//email,read_insights,read_stream,read_mailbox,ads_management,xmpp_login,user_about_me,user_activities,user_birthday,user_education_history,user_events,user_groups,user_hometown,user_interests,user_likes,user_location,user_notes,user_online_presence,user_photo_video_tags,user_photos,user_relationships,user_religion_politics,user_status,user_videos,user_website,user_work_history,read_friendlists,read_requests
			//friends_about_me,friends_activities,friends_birthday,friends_education_history,friends_events,friends_groups,friends_hometown,friends_interests,friends_likes,friends_location,friends_notes,friends_online_presence,friends_photo_video_tags,friends_photos,friends_relationships,friends_religion_politics,friends_status,friends_videos,friends_website,friends_work_history
			
			// API
			fb = new Facebook(clientId, redirectURI, permissions);
			fb.addEventListener(FacebookEvent.ERROR, onFBEvent);
			fb.addEventListener(FacebookEvent.CONNECT, onFBEvent);
			fb.addEventListener(FacebookEvent.CONNECT_ERROR, onFBEvent);
			fb.addEventListener(FacebookEvent.USER_DATA, onFBEvent);
			fb.addEventListener(FacebookEvent.FRIENDS_LIST, onFBEvent);
			fb.addEventListener(FacebookEvent.FEED_DATA, onFBEvent);
			fb.addEventListener(FacebookEvent.PUBLISH_TO_WALL, onFBEvent);
			fb.addEventListener(FacebookEvent.PUBLISH_PHOTO, onFBEvent);
			fb.addEventListener(FacebookEvent.ALBUMS, onFBEvent);
			fb.addEventListener(FacebookEvent.PHOTOS, onFBEvent);
			fb.addEventListener(FacebookEvent.VIDEOS, onFBEvent);
			fb.addEventListener(FacebookEvent.STATUSES, onFBEvent);
			fb.addEventListener(FacebookEvent.LINKS, onFBEvent);
			fb.addEventListener(FacebookEvent.LIKES, onFBEvent);
			fb.addEventListener(FacebookEvent.FANS_COUNT, onFBEvent);
			fb.addEventListener(FacebookEvent.POST_DATA, onFBEvent);
			fb.addEventListener(FacebookEvent.CHECKINS, onFBEvent);
			fb.addEventListener(FacebookEvent.PLACE, onFBEvent);
			fb.addEventListener(FacebookEvent.FRIENDS_NOTIFICATIONS, onFBEvent);
			fb.addEventListener(FacebookEvent.REQUEST_DETAILS, onFBEvent);
			fb.addEventListener(FacebookEvent.DISCONNECT, onFBEvent);
			
			// for an swf app inside facebook, token is passed as a flashvar (see iframe_facebook.php)
			//fb.connectFromFlashVars();
			
			// UI
			addChildWithProps(new SimpleTextButton("FB connect"), { data:"connect", click:onClick } );
			addChildWithProps(new SimpleTextButton("get friends"), { data:"friends", click:onClick } );
			addChildWithProps(new SimpleTextButton("get feed data"), { data:"feed", click:onClick } );
			addChildWithProps(new SimpleTextButton("publish message to wall"), { data:"publish", click:onClick } );
			addChildWithProps(new SimpleTextButton("publish message to wall (using JS sdk)"), { data:"publishJS", click:onClick } );
			addChildWithProps(new SimpleTextButton("publish photo"), { data:"publishPhoto", click:onClick } );
			addChildWithProps(new SimpleTextButton("get albums"), { data:"albums", click:onClick } );
			addChildWithProps(new SimpleTextButton("get photos from album"), { data:"photos", click:onClick } );
			addChildWithProps(new SimpleTextButton("get friend data"), { data:"friend", click:onClick } );
			addChildWithProps(new SimpleTextButton("get videos"), { data:"videos", click:onClick } );
			addChildWithProps(new SimpleTextButton("get links"), { data:"links", click:onClick } );
			addChildWithProps(new SimpleTextButton("get statuses"), { data:"statuses", click:onClick } );
			addChildWithProps(new SimpleTextButton("get likes"), { data:"likes", click:onClick } );
			addChildWithProps(new SimpleTextButton("get fans count"), { data:"fans", click:onClick } );
			addChildWithProps(new SimpleTextButton("get post data (http://www.facebook.com/photo.php?pid=4368489&id=92270828609&ref=mf&fbid=409999093609)"), { data:"post", click:onClick } );
			addChildWithProps(new SimpleTextButton("get checkins"), { data:"checkins", click:onClick } );
			addChildWithProps(new SimpleTextButton("get place informations (publicis net : 120342051353159) "), { data:"place", click:onClick } );
			addChildWithProps(new SimpleTextButton("send notification (using JS sdk)"), { data:"notif", click:onClick } );
			addChildWithProps(new SimpleTextButton("disconnect"), { data:"disconnect", click:onClick } );
		}
		
		private function onFBEvent(e:FacebookEvent):void
		{
			if (e.type == FacebookEvent.FRIENDS_LIST)
			{
				var data:Array = [];
				for (var i:int = 0; i < e.data.length; i++)
				{
					var user:FBUser = FBUser(e.data[i]);
					data.push( { data:user, label:user.name} );
				}
				addChildWithProps(new List(300, 10, MyListRenderer), { data:data, x:300, y:0 } );
			}
			if (e.type == FacebookEvent.FRIENDS_NOTIFICATIONS)
			{
				fb.getRequestDetails(e.data.shift());
			}
			else
			{
				if (e.type == FacebookEvent.CONNECT)
				{
					removeChildAt(0);
					debug("Access token = " + fb.token);
				}
				debug("***********" + e.type + "*************");
				debug(e.data);
			}
		}
		
		private function onClick(e:MouseEvent):void
		{
			switch (e.currentTarget.data)
			{
				case "connect":
					// normal connect, will open a HTML popup for login & permissions request
					fb.connect();
					
					// if app is in HTML page containing the FB javascript SDK, will open a light box for login & permissions request
					//fb.connectFromJS();
					
					// if app is in a page that already has a token passed to the swf via flashvars
					//fb.connectFromFlashVars();
					
					// if app has offline_access permission, the token can be used at any time to connect the user.
					// Use during development process so no ExternalInterface is needed and swf can be tested in simple flash player.
					//fb.connectFromToken("my_token");
					
					break;
				case "friend":
					fb.getUserData("630501226");
					break;
				case "feed":
					fb.getFeedData();
					break;
				case "friends":
					fb.getFriendsList();
					break;
				case "albums":
					fb.getAlbums();
					break;
				case "videos":
					fb.getVideos();
					break;
				case "links":
					fb.getLinks();
					break;
				case "statuses":
					fb.getStatuses();
					break;
				case "likes":
					fb.getLikes();
					break;
				case "photos":
					fb.getPhotos("106683519390634");
					break;
				case "fans":
					fb.getFansCount("cocacola");
					break;
				case "post":
					fb.getPostData("409999093609");
					break;
				case "publish":
					var post:FBPost = new FBPost();
					post.type = FBPost.TYPE_SWF;
					post.message = "test message " + new Date();
					post.description = "my description";
					post.link = "http://www.facebook.com";
					post.picture = "http://contents.frequencebanane.ch/image/geneve/flash-player_logo.jpg";
					post.source = "http://uploads.ungrounded.net/547000/547731_ANDTD_tribute.swf";
					
					// SWF file on FB Wall has an fixed width of 520px.
					
					fb.publishToWall(post);
					break;
				case "publishPhoto":
					var jpeg:ByteArray = JPEGEncoder.encode(Plugin.plugin.assetManager.getBitmapDataAsset("swf.gfx.Header"));
					fb.publishPhoto(jpeg, "test message " + new Date());
					break;
				case "checkins":
					fb.getCheckins();
					break;
				case "place":
					fb.getPlace("120342051353159");
					break;
				case "notif":
					fb.sendJSNotifications("titre", "message", 3);
					break;
				case "publishJS":
					var jsPost:FBPost = new FBPost();
					jsPost.name = "my name";
					jsPost.message = "test message " + new Date();
					jsPost.description = "my description";
					jsPost.link = "http://www.facebook.com";
					jsPost.picture = "http://contents.frequencebanane.ch/image/geneve/flash-player_logo.jpg";
					fb.publishJSToWall(jsPost);
				case "disconnect":
					fb.disconnect();
					break;
			}
			
		}
		
	}
}



// special renderer for friends list

import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
import marcel.debug.*;
import marcel.display.gui.components.ListItemRenderer;

class MyListRenderer extends ListItemRenderer
{
	private var _loader:Loader;
	private var _pic:String;
	private var _int:uint;
	
	public function MyListRenderer()
	{
		super();
		
		_loader = new Loader();
		_loader.x = 3;
		_loader.y = 2;
		_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
		addChild(_loader);
	}
	
	private function onLoaded(e:Event):void
	{
		_loader.width = 16;
		_loader.height = 16;
	}
	
	override public function setData(data:Object):void
	{
		if (_pic != data.pic_square)
		{
			_pic = data.pic_square;
			_loader.visible = false;
			clearTimeout(_int);
			_int = setTimeout(loadImage, 100); // timeout to not make http request on each scroll...
		}
	}
	
	private function loadImage():void
	{
		try { _loader.close(); } catch (e:Error) { };
		_loader.load(new URLRequest(_pic));
		_loader.visible = true;
	}
	
	override public function set width(w:Number):void
	{
		_bg.width = w;
		_label.width = w - 25;
		_label.x = 20;
		if (_arrow) _arrow.x = _bg.width - _arrow.width - 5;
	}
}